package com.cml.sqlversionupgradestarter.service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 作者：陈茂林
 * 时间：2022/1/6
 * 描述：
 */
public class JdbcConnManager {
    private  DataSource dataSource;
    private static ThreadLocal<Connection> connction = new ThreadLocal();

    public   void setDataSource(DataSource dataSource){
        this.dataSource=dataSource;
    }

    public  synchronized Connection getConnection() throws SQLException {
        Connection connection = JdbcConnManager.connction.get();
        if(connection == null){
            connection= this.dataSource.getConnection();
            JdbcConnManager.connction.set(connection);
        }
        return connection;
    }

    public  synchronized void closeConnection(Connection connection){
        try {
            connection.close();

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcConnManager.connction.remove();
        }
    }
}
